package com.wtao.testcamera;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import org.videolan.libvlc.LibVLC;
import org.videolan.libvlc.Media;
import org.videolan.libvlc.MediaPlayer;
import org.videolan.libvlc.util.VLCVideoLayout;
import org.webrtc.Camera1Enumerator;
import org.webrtc.Camera2Enumerator;
import org.webrtc.CameraEnumerator;
import org.webrtc.DefaultVideoDecoderFactory;
import org.webrtc.DefaultVideoEncoderFactory;
import org.webrtc.EglBase;
import org.webrtc.PeerConnectionFactory;
import org.webrtc.RendererCommon;
import org.webrtc.SurfaceTextureHelper;
import org.webrtc.SurfaceViewRenderer;
import org.webrtc.VideoCapturer;
import org.webrtc.VideoDecoderFactory;
import org.webrtc.VideoEncoderFactory;
import org.webrtc.VideoSource;
import org.webrtc.VideoTrack;

/**
 *
 */
public class WebRtcActivity extends AppCompatActivity{
    private String VIDEO_TRACK_ID = "0"; //"ARDAMSv0"

    private int VIDEO_RESOLUTION_WIDTH = 1920;
    private int VIDEO_RESOLUTION_HEIGHT = 1080;
    private int VIDEO_FPS = 30;


    //    绘制全局的上下文
    private EglBase rootEglBase = null;
    private VideoTrack mVideoTrack  = null;

    private PeerConnectionFactory mPeerConnectionFactory = null;

    //纹理渲染
    private SurfaceTextureHelper mSurfaceTextureHelper  = null;

    private VideoCapturer mVideoCapture= null;

    private SurfaceViewRenderer camera_preview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_rtc);
        camera_preview = findViewById(R.id.camera_preview);
        findViewById(R.id.btnBack).setOnClickListener(v->{
            finish();
        });

        rootEglBase = EglBase.create();

        camera_preview.init(rootEglBase.getEglBaseContext(), null);

        //悬浮顶端
        camera_preview.setZOrderMediaOverlay(true);
        //硬件加速
        camera_preview.setEnableHardwareScaler(true);
        camera_preview.setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FILL);

        mPeerConnectionFactory = createPeerConnectionFactory(WebRtcActivity.this);

        mVideoCapture = createVideoCapture();

        // 初始化
        mSurfaceTextureHelper = SurfaceTextureHelper.create("CaptureThread", rootEglBase.getEglBaseContext());
        // 创建VideoSource
        VideoSource videoSource = mPeerConnectionFactory.createVideoSource(false);
        mVideoCapture.initialize(
                mSurfaceTextureHelper,
                getApplicationContext(),
                videoSource.getCapturerObserver()
        );

        mVideoTrack = mPeerConnectionFactory.createVideoTrack(VIDEO_TRACK_ID,
                videoSource
        );
        mVideoTrack.setEnabled(true);
        mVideoTrack.addSink(camera_preview);

    }

    /**
     * 创建PeerConnectionFactory
     */
    private PeerConnectionFactory createPeerConnectionFactory(Context context) {

        VideoDecoderFactory decoderFactory;
        VideoEncoderFactory encoderFactory = new DefaultVideoEncoderFactory(
                rootEglBase.getEglBaseContext(),
        false /* enableIntelVp8Encoder */,
                true
        );
        decoderFactory = new DefaultVideoDecoderFactory(rootEglBase.getEglBaseContext());
        PeerConnectionFactory.initialize(
                PeerConnectionFactory.InitializationOptions.builder(context)
                        .setEnableInternalTracer(true)
                        .createInitializationOptions()
        );
        PeerConnectionFactory.Builder builder = PeerConnectionFactory.builder()
                .setVideoEncoderFactory(encoderFactory)
                .setVideoDecoderFactory(decoderFactory);
        builder.setOptions(null);
        return builder.createPeerConnectionFactory();
    }

    private VideoCapturer createVideoCapture()  {
         if (Camera2Enumerator.isSupported(this)) {
             return createCameraCapture(new Camera2Enumerator(this));
        } else {
             return createCameraCapture(new Camera1Enumerator(true));
        }
    }

    private VideoCapturer createCameraCapture(CameraEnumerator enumerator ) {
        String[] deviceNames = enumerator.getDeviceNames();
        // First, try to find front facing camera
        for (String deviceName : deviceNames) {
            if (enumerator.isFrontFacing(deviceName)) {

                VideoCapturer videoCapture = enumerator.createCapturer(deviceName, null);
                if (videoCapture != null) {
                    return videoCapture;
                }
            }
        }

        for (String deviceName : deviceNames) {
            if (!enumerator.isFrontFacing(deviceName)) {
                VideoCapturer videoCapture  = enumerator.createCapturer(deviceName, null);
                if (videoCapture != null) {
                    return videoCapture;
                }
            }
        }
        return null;
    }

    public void onResume() {
        super.onResume();
        // 开启摄像头预览
        mVideoCapture.startCapture(
                VIDEO_RESOLUTION_WIDTH,
                VIDEO_RESOLUTION_HEIGHT,
                VIDEO_FPS
        );
    }
}